(function (window, $, undefined) {
  'use strict';

  var dictData = {
    orderType: [],
    vehiclePurpose: [],
    availableCity: [],
    fareType: [],
    orderChannel: [],
    userType: []
  };

  var couponTypeData = {};

  main(function () {

    var $tableCouponType = $('#table-coupon-type');

    util.jqGrid($tableCouponType, {
      url: ajaxURL.COUPON + '/coupon/getCouponTypeList',
      // datatype: 'json',
      mtype: 'GET',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { label: '序号', name: 'kid', key: true, width: 50, fixed: true },
        { label: '方案名称', name: 'couponName', width: 100 },
        {
          label: '编号抬头',
          name: 'numbered',
          width: 120
        },
        { label: '面额(元)', name: 'money', width: 100, formatter: function (v) {
          return v / 100;
        } },
        {
          label: '最低结算金额(元)',
          name: 'trigger',
          width: 100,
          formatter: function (v) {
            return v / 100;
          }
        },
        { label: '是否支持折后使用', name: 'discountFlag', width: 150, formatter: function (v) {
          return +v === 1 ? '是' : '否';
        }
        },
        {
          label: '领取有效期', name: 'validityTime', width: 220, formatter: function (v, o, r) {

            var now = util.getTime(util.getDate(true) + ' 00:00:00');
            var ret = util.getDate(r.validityStartTime) + ' 至 ' + util.getDate(r.validityEndTime);
            if (now > r.validityEndTime) {
              ret += ' (<span class="text-danger">已过期</span>)';
            }
            return ret;
          }
        },
        { label: '备注', name: 'remark', width: 100 }
      ],
      loadComplete: function (res) {
        couponTypeData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            couponTypeData[item.kid] = item;
          });
        }
      },
      pager: '#pager-coupon-type'
    });

    var dictList = [
      'orderType',
      'vehiclePurpose',
      'fareType',
      'orderChannel',
      'useType'
    ];

    var dictName = [
      'orderType',
      'vehiclePurpose',
      'fareType',
      'orderChannel',
      'userType'
    ];

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      dictData.availableCity = res.data;

      util.selectHtml('select[name="availableCity"]', res.data, 'cityId', 'name', '全部');

      // 获取字典表数据
      util.getDicts(dictList).then(function (datas) {

        util.selectHtml('select[name="orderChannel"]', datas[3], 'value', 'name', '全部');
        util.selectHtml('select[name="orderType"]', datas[0], 'value', 'name', '全部');

        $.each(datas, function (_, item) {
          dictData[dictName[_]] = item;
        });

        renderCheckbox();

        searchTable();
        $('#btn-search').click(searchTable);
      });
    });

    // 搜索
    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tableCouponType, {
        useChannelOot: data.orderChannel,
        couponNameLike: data.couponNameLike,
        numbered: data.numbered,
        orderTypeOot: data.orderType,
        availableCityOot: data.availableCity
      });
    }

    // 有效期
    laydate.render({
      range: '至',
      elem: '#validityTime'
    });
    laydate.render({
      range: '至',
      elem: '#useTime'
    });

    var $layerType = $('#layer-type-detail');
    var $formType = $('#form-type-detail');

    var $validateType = $formType.validate({
      rules: {
        numbered: { required: true, maxlength: 20 },
        codeType: { required: true },
        startNum: { required: true, digits: true, min: 1, max: 9999999 },
        cumulativeNum: { required: true, digits: true, min: 1, max: 9999999 },
        money: { required: true, digits: true, min: 1, max: 9999999 },
        couponName: { required: true, maxlength: 50 },
        trigger: { required: true, digits: true, min: 0, max: 9999999 },
        discountFlag: { required: true },
        validityTime: { required: true },
        useValidityType: { required: true },
        useTime: { required: true },
        invalidDate: { required: true, digits: true, min: 1, max: 999 },
        remark: { maxlength: 200 },
        orderType: { required: true },
        vehiclePurpose: { required: true },
        fareType: { required: true },
        orderChannel: { required: true },
        userType: { required: true },
        availableCity: { required: true }
      },
      messages: {

      },
      errorPlacement: function (error, element) { // 错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); // 这里的element是录入数据的对象
      }
    });

    // 切换显隐的动态效果
    $formType.on('click', '[name="useValidityType"]', function () {
      var $this = $(this);
      if ($this.val() === '1') {
        $('#type-useTime').removeClass('hide');
        $('#type-invalidDate').addClass('hide');
      } else {
        $('#type-useTime').addClass('hide');
        $('#type-invalidDate').removeClass('hide');
      }
    });
    $formType.on('click', '[name="codeType"]', function () {
      var $this = $(this);
      var $types = $formType.find('.check-code-type');
      if ($this.val() === '1') {
        $types.addClass('hide');
      } else {
        $types.removeClass('hide');
      }
    });

    // 新建代金券
    $('#btn-add').click(function () {
      util.resetForm($formType);
      $formType.find('input').removeAttr('disabled');

      // 隐藏检查显示的数据
      $formType.find('.check-show').addClass('hide');

      util.layerOpen2({
        // title: '新增代金券类型',
        title: false,
        content: $layerType,
        area: ['1200px', '600px'],
        btn: ['确认新建', '取消'],
        yes: function (index) {
          saveCouponData();
        }
      }, '正在创建代金券，是否退出？');
    });

    // 查看/修改
    $('#btn-edit').click(util.oneCheck($tableCouponType, function (id) {
      var curData = couponTypeData[id];

      util.get(ajaxURL.COUPON + '/coupon/getCouponTypeList?kid=' + id, function (res) {
        util.resetForm($formType);
        $formType.find('input').removeAttr('disabled');
        // 隐藏
        $formType.find('.check-show').addClass('hide');
        var data = res.data[0];

        // 显示单选的联动元素
        $formType.find('[name="useValidityType"][value="' + data.useValidityType + '"]').click();
        $formType.find('[name="codeType"][value="' + data.codeType + '"]').click();

        // 时间戳的处理
        if (data.validityStartTime && data.validityEndTime) {
          data.validityTime = util.getDate(data.validityStartTime) + ' 至 ' + util.getDate(data.validityEndTime);
        }
        if (data.useStartTime && data.useEndTime) {
          data.useTime = util.getDate(data.useStartTime) + ' 至 ' + util.getDate(data.useEndTime);
        }

        // 金额转为元
        data.trigger /= 100;
        data.money /= 100;

        util.fillForm($formType, data);

        // 勾选已选择的范围设置
        $formType.find('.range-set').each(function (index, elem) {
          var $elem = $(elem);
          var name = $elem.attr('id').replace('sel-', '');
          var rangeData = data[name] + '';
          var $inputs = $elem.find('input');
          var len = $inputs.length - 1;

          var curRange = rangeData.split(',');

          if (+rangeData === 0) { // 通用
            $inputs.eq(0).prop('checked', true);
            $inputs.filter(':gt(0)').attr('disabled', true);
          } else {
            $inputs.each(function (index, item) {
              var $cur = $(this);
              var _val = $cur.val();
              $cur.prop('checked', curRange.indexOf(_val) > -1);
            });
          }

        });

        util.layerOpen2({
          // title: '查看/修改代金券类型',
          title: false,
          content: $layerType,
          area: ['1200px', '600px'],
          btn: ['修改', '取消'],
          yes: function (index) {
            saveCouponData(id);
          }
        });
      });
    }));

    // 新增/保存代金券类型
    function saveCouponData(kid) {
      var data = util.formData($formType);

      kid = kid || '';

      // 金额转为分
      data.trigger *= 100;
      data.money *= 100;

      // 提交给后台的数据拼装
      var postData = {
        kid: kid,
        couponId: kid,
        money: data.money,
        codeType: data.codeType,
        couponName: data.couponName,
        cumulativeNum: data.cumulativeNum,
        discountFlag: data.discountFlag,
        invalidDate: data.invalidDate,
        trigger: data.trigger,
        numbered: data.numbered,
        remark: data.remark,
        startNum: data.startNum,
        status: 101,
        useValidityType: data.useValidityType
      };

      // 时间戳处理
      if (data.validityTime) {
        var temp1 = data.validityTime.split(' 至 ');
        postData.validityStartTime = util.getTime(temp1[0] + ' 00:00:00');
        postData.validityEndTime = util.getTime(temp1[1] + ' 23:59:59');
      }
      if (data.useTime) {
        var temp2 = data.useTime.split(' 至 ');
        postData.useStartTime = util.getTime(temp2[0] + ' 00:00:00');
        postData.useEndTime = util.getTime(temp2[1] + ' 23:59:59');
      }

      postData.couponCode = postData.numbered;

      if (kid) {
        postData.updateId = oUser.userId;
        postData.updateTime = $.now();
      } else {
        postData.createId = oUser.userId;
        postData.createTime = $.now();
      }

      // 拼装范围设置数据
      $formType.find('.range-set').each(function (index, elem) {
        var $elem = $(elem);
        var name = $elem.attr('id').replace('sel-', '');
        var $inputs = $elem.find('input');
        var isAll = $inputs.eq(0).prop('checked');
        var len = $inputs.length;
        var ret = [];

        if (isAll) {
          postData[name] = '0';
        } else {
          for (var i = 1; i < len; i++) {
            var $cur = $inputs.eq(i);
            if ($cur.prop('checked')) {
              ret.push($cur.val());
            }
          }
          postData[name] = ret.join();
        }

      });

      // console.log(postData, data)

      var url = ajaxURL.COUPON + (kid ? '/coupon/updateCouponType' : '/coupon/addCouponType');

      if ($validateType.form()) {

        layer.confirm('确定提交当前数据？', function () {
          util.post(url, postData, function (res) {
            layer.closeAll();
            util.tip.success((kid ? '修改' : '新增') + '成功');
            $tableCouponType.trigger('reloadGrid');
          });
        });
      } else {
        util.tip.warn('数据填写有误，请更正后重新提交');
      }
    }

    // 生成备选框的 html 代码
    function genSelHtml(data, name) {
      var ret = '<label class="marginR10"><input class="all" name="' + name + '" type="checkbox" value="0" />通用</label>';
      $.each(data, function (_, item) {
        ret += '<label class="marginR10">';
        ret += '<input value="' + (item.cityId || item.value) + '" name="' + name + '" type="checkbox" />';
        ret += item.name;
        ret += '</label>';
      });
      return ret;
    }
    // 渲染代金券详情页面的备选框
    function renderCheckbox() {
      $('#sel-orderType').html(genSelHtml(dictData.orderType, 'orderType'));
      $('#sel-vehiclePurpose').html(genSelHtml(dictData.vehiclePurpose, 'vehiclePurpose'));
      $('#sel-fareType').html(genSelHtml(dictData.fareType, 'fareType'));
      $('#sel-orderChannel').html(genSelHtml(dictData.orderChannel, 'orderChannel'));
      $('#sel-userType').html(genSelHtml(dictData.userType, 'userType'));
      $('#sel-availableCity').html(genSelHtml(dictData.availableCity, 'availableCity'));
    }

    // 选择通用的时候的联动效果
    $formType.on('click', '.all', function () {
      var $this = $(this);
      var $siblings = $this.parent().siblings().find('input');
      var checked = $this.prop('checked');

      if (checked) {
        $siblings.attr('disabled', 'disabled');
      } else {
        $siblings.removeAttr('disabled');
      }

    });


  });
})(window, jQuery);
